//
//  HomeViewController.m
//  quxiangtao
//
//  Created by E人一铺 on 2018/11/15.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "HomeViewController.h"
#import "CenterTouchTableView.h"
#import "HomeCollectionView.h"
#import "HomeHeaderView.h"
#import "SegmentView.h"
#import "HSUpdateApp.h"
#import "SearchViewController.h"
#import "QNetWorkRequest.h"

@interface HomeViewController () <UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

@property (nonatomic, strong) CenterTouchTableView *mainTableView;
@property (nonatomic, strong) HomeHeaderView *mainTableViewHeaderView;
@property (nonatomic, strong) SegmentView *mainTableViewFooterView;
@property (nonatomic, copy)NSString*webViewUrl;
@property (nonatomic, assign) BOOL canScroll; //mainTableView是否可以滚动


// 导航栏白色背景的透明度
@property (assign, nonatomic) CGFloat alpha;
@property (strong, nonatomic) UIView *navBgView;

@property (nonatomic,strong) UIImageView *backIcon;


@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //如果使用自定义的按钮去替换系统默认返回按钮，会出现滑动返回手势失效的情况
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self setupSubViews];
    
    //注册允许外层tableView滚动通知-解决和分页视图的上下滑动冲突问题
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:@"leaveTop" object:nil];
    
    //切换分页时禁止mainTableView上下滑动，停止分页左右滑动的时候允许mainTableView滑动
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:IsEnablePersonalCenterVCMainTableViewScroll object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(btnViewClick:) name:@"NSNotificationTopClick" object:nil];
    
//    UIImageView *imageimage = [[UIImageView alloc] init];
//    imageimage.userInteractionEnabled = YES;
//    [self.view addSubview:imageimage];
//    [imageimage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.mas_equalTo(-20);
//        make.bottom.mas_equalTo(-Height_TabBar-30);
//        make.size.mas_equalTo(CGSizeMake(50, 50));
//    }];
//
//    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView)];
//    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
//    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
//    imageimage.contentMode = UIViewContentModeScaleToFill;
//    [imageimage addGestureRecognizer:PrivateLetterTap];
    
    
    NSString *string = [NSString stringWithFormat:@"{\"userid\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].isLogin ? [CommonUserInfo sharedInstance].user_id : @"0" publicKey:PublicKey]];
    WS(weakSelf);
    [PPNetworkHelper POST:@"index/Share/index" parameters:@{@"json":string} success:^(id responseObject) {
        
//        if ([responseObject[@"code"] intValue] == 110) {
//            imageimage.hidden = YES;
//        }
//        if ([responseObject[@"code"] intValue] == 1) {
//            imageimage.hidden = NO;
//            [imageimage sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"image"]]];
//            weakSelf.webViewUrl = responseObject[@"data"][@"url"];
//        }
    } failure:^(NSError *error) {
        
    }];
    
    [self uploadVersion];
    
}

- (void)uploadVersion {
    [HSUpdateApp hs_updateWithAPPID:@"1434802834" withBundleId:nil block:^(NSString *currentVersion, NSString *storeVersion, NSString *openUrl, BOOL isUpdate) {
        if (isUpdate) {
            [self showAlertViewTitle:@"版本检测" subTitle:[NSString stringWithFormat:@"检测到新版本%@,请您更新",storeVersion] openUrl:openUrl];
        }else{
            NSLog(@"当前版本%@,商店版本%@，不需要更新",currentVersion,storeVersion);
        }
    }];
}


-(void)showAlertViewTitle:(NSString *)title subTitle:(NSString *)subTitle openUrl:(NSString *)openUrl{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
                    }];
                } else {
                }
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl]];
            }
        } else{
            bool can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]];
            if(can){
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl]];
            }
        }
    }];
    [alertVC addAction:sure];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)tapAvatarView{
    
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        return;
    }
    WebViewController *webVc = [[WebViewController alloc] init];
    webVc.url = self.webViewUrl;
    [self.navigationController pushViewController:webVc animated:YES];
}


- (void)btnViewClick:(NSNotification *)notification {
    
    NSDictionary *dict = notification.object;
    NSInteger tag = [dict[@"tag"] integerValue];
    if (tag != 0) {
        [self.mainTableViewFooterView setViewIsSelfSupportwithTag:tag];
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [TalkingData trackPageBegin:@"购物页"];
    self.navBgView.alpha = 0;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [TalkingData trackPageEnd:@"购物页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)acceptMsg:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    
    if ([notification.name isEqualToString:@"leaveTop"]) {
        NSString *canScroll = userInfo[@"canScroll"];
        if ([canScroll isEqualToString:@"1"]) {
            self.canScroll = YES;
        }else {
            
        }
    } else if ([notification.name isEqualToString:IsEnablePersonalCenterVCMainTableViewScroll]) {
        NSString *canScroll = userInfo[@"canScroll"];
        if ([canScroll isEqualToString:@"1"]) {
            self.mainTableView.scrollEnabled = YES;
        } else if ([canScroll isEqualToString:@"0"]) {
            self.mainTableView.scrollEnabled = NO;
        }
    }
}

#pragma mark - UITableViewDelegate
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    //通知分页子控制器列表返回顶部
    [[NSNotificationCenter defaultCenter] postNotificationName:SegementViewChildVCBackToTop object:nil];
    return YES;
}

/**
 * 处理联动
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //当前偏移量
    CGFloat currentOffsetY = scrollView.contentOffset.y;
    //吸顶临界点(此时的临界点不是感官上导航栏的底部，而是屏幕的顶部)
    CGFloat criticalPointOffsetY = scrollView.contentSize.height - SCREEN_HEIGHT;

    //利用contentOffset处理内外层scrollView的滑动冲突问题
    /* 主要规则：
     * ⚠️ 这里的”吸顶状态“和”到达临界点状态“不能完全划等号，这里一下子确实有点难以理解，我会在下方尽可能的简单   化表达出来
     * 一、吸顶状态: segmentView到达临界点(这里设置的临界点是导航栏底部，可以自定义))
     mainTableView不能滚动(固定mainTableView的位置-通过设置contentOffset的方式),segmentView的子控制器的tableView或collectionView在竖直方向上可以滚动；
     二、未吸顶状态:
     mainTableView能滚动,segmentView的子控制器的tableView或collectionView在竖直方向上不可以滚动；
     */
    if (currentOffsetY >= criticalPointOffsetY) {
        /*
         * 到达临界点 ：此状态下有两种情况
         * 1.未吸顶状态 -> 吸顶状态
         * 2.维持吸顶状态 (segmentView的子控制器的tableView或collectionView在竖直方向上的contentOffsetY大于0)
         */
        self.mainTableView.frame = CGRectMake(0, Height_StatusBar, SCREEN_WIDTH, SCREEN_HEIGHT);
        //下面这行代码是“维持吸顶状态”和“进入吸顶状态”的共同代码
        scrollView.contentOffset = CGPointMake(0, criticalPointOffsetY);
        //进入吸顶状态
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goTop" object:nil userInfo:@{@"canScroll":@"1"}];
        self.canScroll = NO;
    } else {
        /*
         * 未达到临界点 ：此状态下有两种情况，且这两种情况完全相反，这也是引入一个canScroll属性的重要原因
         * 1.吸顶状态 -> 不吸顶状态
         * 2.维持吸顶状态 (segmentView的子控制器的tableView或collectionView在竖直方向上的contentOffsetY大于0)
         */

        if (!self.canScroll) {
            //维持吸顶状态
            scrollView.contentOffset = CGPointMake(0, criticalPointOffsetY);
        } else {
            self.mainTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            /* 吸顶状态 -> 不吸顶状态
             * segmentView的子控制器的tableView或collectionView在竖直方向上的contentOffsetY小于等于0时，会通过通知的方式改变self.canScroll的值；
             * 这里不再做多余处理，已经在SegmentViewController中做了处理-发送name为“leaveTop”的通知
             */
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeCollectionView *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HomeCollectionView class]) forIndexPath:indexPath];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    headerView.backgroundColor = [UIColor yellowColor];
    UILabel *titleLB = [UILabel new];
    titleLB.font = [UIFont boldSystemFontOfSize:18];
    if (section == 0) {
        titleLB.text = @"第一分区";
    } else {
        titleLB.text = @"第二分区";
    }
    [headerView addSubview:titleLB];
    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.mas_equalTo(15);
        make.bottom.mas_equalTo(-10);
        make.width.mas_equalTo(150);
    }];
    return headerView;
}

- (void)setSelectIndex:(NSInteger)selectIndex {
    
    _selectIndex = selectIndex;
    self.mainTableViewHeaderView.selectIndex = selectIndex;
    [self.mainTableViewHeaderView getTbNavgationTitleData:selectIndex];
}

- (void)setupSubViews {
    
    [self.view addSubview:self.mainTableView];
    [self.mainTableView addSubview:self.mainTableViewHeaderView];
    
    WS(weakSelf)
    self.mainTableViewFooterView.updataBlock = ^{
        SearchViewController *searchCtr = [[SearchViewController alloc] init];
//        searchCtr.categoryType = weakSelf.mainTableViewHeaderView.selectIndex-1;
        searchCtr.categoryType = 1;
        [weakSelf.navigationController pushViewController:searchCtr animated:NO];
    };
    
    self.mainTableViewHeaderView.buttonSelectIndexBlock = ^(NSInteger index) {
        weakSelf.mainTableViewFooterView.selectIndex = index;
    };

    
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
//    [self.header beginRefreshing];
    [self.header setTitle:@"下拉可以刷新!" forState:MJRefreshStateIdle];
    [self.header setTitle:@"松手立即刷新!" forState:MJRefreshStatePulling];
    [self.header setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    self.header.stateLabel.font = Font(24);
    self.header.stateLabel.textColor = Color999999;
    self.header.lastUpdatedTimeLabel.hidden = YES;
    self.mainTableView.mj_header = self.header;
    
//    [self.view addSubview:self.backIcon];
//    
//    [self.backIcon mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(weakSelf.view.mas_top).with.offset(50);
//        make.left.mas_equalTo(weakSelf.view.mas_left).with.offset(20);
//        make.width.mas_equalTo(jisuan(50));
//        make.height.mas_equalTo(jisuan(50));
//        
//    }];
}

- (void)loadNewData {
    
    [self.mainTableViewHeaderView loadData];
}

- (HomeHeaderView *)mainTableViewHeaderView {
    if (!_mainTableViewHeaderView) {
        
        CGFloat height = (IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) ? jisuan(610) : (kDevice_Is_iPhone6Plus) ? jisuanH(560) : (kDevice_Is_iPhone5) ? jisuanH(720) : jisuanH(610);

        _mainTableViewHeaderView = [[HomeHeaderView alloc] initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, height)];
        // 460
        _mainTableViewHeaderView.parentVC = self;
    }
    return _mainTableViewHeaderView;
}

- (SegmentView *)mainTableViewFooterView {
    if (!_mainTableViewFooterView) {
        _mainTableViewFooterView = [[SegmentView alloc] init];
        _mainTableViewFooterView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _mainTableViewFooterView.backgroundColor = Colorf2f2f2;
        _mainTableViewFooterView.parentVC = self;
    }
    return _mainTableViewFooterView;
}

- (UITableView *)mainTableView {
    if (!_mainTableView) {
        //⚠️这里的属性初始化一定要放在mainTableView.contentInset的设置滚动之前, 不然首次进来视图就会偏移到临界位置，contentInset会调用scrollViewDidScroll这个方法。
        //初始化变量
        self.canScroll = YES;
        
        _mainTableView = [[CenterTouchTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.tableHeaderView = self.mainTableViewHeaderView;
        _mainTableView.tableFooterView = self.mainTableViewFooterView;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainTableView.showsVerticalScrollIndicator = NO;
        [_mainTableView registerClass:[HomeCollectionView class] forCellReuseIdentifier:NSStringFromClass([HomeCollectionView class])];
    }
    return _mainTableView;
}

- (UIImageView *)backIcon {
    
    if (!_backIcon) {
        _backIcon = [[UIImageView alloc] init];
        _backIcon.image = [UIImage imageNamed:@"椭圆形"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back:)];
        [_backIcon addGestureRecognizer:tap];
        
        
    }
    return _backIcon;
}
- (void)back:(UIGestureRecognizer *)gesture {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (UIView*)navBgView {
    
    if (!_navBgView) {
        _navBgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height + Height_StatusBar)];
        [self.navigationController.view insertSubview:_navBgView belowSubview:self.navigationController.navigationBar];
    }
    return _navBgView;
    
}


@end
